package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"gochat/common"
	"gochat/domain/request"
	"gochat/domain/response/result"
	"gochat/models"
	"gochat/service"
	"gochat/utils"
	"log"
	"net/http"
	"strconv"
)

var upgrader = websocket.Upgrader{
	// 允许跨域
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func FriendRequest(c *gin.Context) {
	var body request.SendFriendRequest
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		log.Println(err)
		result.Fail(c, 400, "参数错误")
		return
	}

	uid, _ := c.Get("uid")
	body.SendId = uid.(string)
	if body.SendId == body.ReceiveId {
		result.Fail(c, 400, "不能添加自己为好友")
		return
	}
	sendId, err := strconv.Atoi(body.SendId)
	if err != nil {
		result.Fail(c, 400, "参数错误")
		return
	}
	receiveId, err := strconv.Atoi(body.ReceiveId)
	if err != nil {
		result.Fail(c, 400, "参数错误")
		return
	}
	service.Friend.FriendRequest(c, uint(sendId), uint(receiveId), body.Message)
}

func ReceiveFriendRequest(c *gin.Context) {
	uid, exists := c.Get("uid")
	if !exists {
		log.Println("uid不存在")
		return
	}
	id := uid.(string)
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("ws升级失败")
		return
	}
	service.Friend.ReceiveFriendRequest(conn, id)
}

func AcceptFriendRequest(c *gin.Context) {
	friendReqId := c.Param("id")
	status := c.Param("status")
	if status != "1" && status != "2" {
		result.Fail(c, 400, "参数错误")
		return
	}
	uid, _ := c.Get("uid")
	var req models.FriendRequest
	tx := common.DB.Model(&models.FriendRequest{}).
		Where("id=? AND receiver_id=? AND status =0", friendReqId, uid).
		First(&req)
	if tx.RowsAffected == 0 {
		result.Fail(c, 400, "对方并未向你发送好友申请")
		return
	}
	service.Friend.AcceptFriendRequest(c, friendReqId, status)
}

// FriendList 我的好友列表/*
func FriendList(c *gin.Context) {
	uid, err := utils.GetUid(c)
	if err != nil {
		result.Fail(c, 400, "参数错误")
		return
	}
	service.Friend.FriendListByUid(c, uid)
}
